<template>
  <div
    class="codeBtn pointer"
    @click="sendCode"
    :class="{ disable: disableCode }"
  >
    {{ sendBtnText }}
  </div>
</template>

<script>
export default {
  name: "HomeView",
  data() {
    return {
      sendBtnText: "获取验证码",
      disableCode: false,
      timer: null,
    };
  },
  props: {
    email: {
      default: "",
    },
    event: {
      default: "",
    },
  },
  methods: {
    sendCode() {
      if (!this.disableCode) {
        this.$post("/ems/send", {
          email: this.email,
          event: this.event,
        }).then((res) => {
          if (res.code == 1) {
            if (!this.disableCode) {
              this.countDown();
            }
            this.disableCode = true;
            this.$message.success(res.msg);
          } else {
            // this.$toast(res.msg);
            // this.$message.error(res.msg);
          }
        });
      }
    },
    countDown() {
      let counter = 60;
      // 将setInterval()方法赋值给前面定义的timer计时器对象，等用clearInterval()方法时方便清空这个计时器对象
      this.sendBtnText = `已发送(${counter}秒)`;
      this.timer = setInterval(() => {
        this.sendBtnText = `已发送(${counter - 1}秒)`;
        counter--;
        if (counter == 0) {
          // 当计时小于零时，取消该计时器
          clearInterval(this.timer);
          this.disableCode = false;
          this.sendBtnText = `重新发送`;
        }
      }, 1000);
    },
  },
};
</script>
<style lang="scss" scoped>
.codeBtn {
  color: #440f52;
  line-height: 41px;
  position: absolute;
  top: 0;
  right: 0;
  font-size: 16px;
  padding: 0 10px;
}
.disable {
  opacity: 0.5;
}
</style>
